package cpa.prowon.gui.util;

import java.net.MalformedURLException;
import java.net.URL;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.graphics.Image;

/**
 * The image util class is used to administrate the image registry,
 * generate thumbnails etc. 
 * @author Chris
 */
public class ImageUtil {

	// Properties
	private static ImageRegistry image_registry;

	/**
	 * Return the image registry, if it was not yet created it gets created
	 * @return The ImageRegistry object
	 * @author Chris
	 */
	protected static ImageRegistry getImageRegistry() {
		
		// If the image registry was not created yet, create it
		if (image_registry == null) {
			image_registry = new ImageRegistry();
		}
		
		// Return the image registry
		return image_registry;
		
	}

	/**
	 * Return the image with the specified name. The mechanism behind is that the
	 * ImageRegistry is used to cache and share images
	 * @param String The file name of the image, to be specified without "file:"
	 * @return The Image object
	 * @author Chris
	 */
	public static Image getImage(String imageFileName) {
		
		// Try to get the image from the image registry first
		Image image = getImageRegistry().get(imageFileName);
		
		// If it's not available via the registry, get the image and put it in the registry
		if (image == null) {
			try {
				getImageRegistry().put(
					imageFileName, 
					ImageDescriptor.createFromURL(new URL("file:"+imageFileName))
				);
				image = getImageRegistry().get(imageFileName);
			} catch (MalformedURLException e) {
				throw new RuntimeException("Malformed URL");
			}
		}
		
		// Return the image
		return image;
		
	}

	/**
	 * Return an URL object for the specified URL name
	 * @param String The name of the URL
	 * @return URL The actual URL object
	 * @author Chris
	 */
	public static URL getURL(String url_name) {
		try {
			return new URL(url_name);
		} catch (MalformedURLException e) {
			throw new RuntimeException("Malformed URL " + url_name, e);
		}
	}
	
}
